package com.useeinfo.framework.sugar.tools;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

/**
 * Author: 居泽平  Date: 13-7-6, 上午9:33
 */
@SuppressWarnings("unused")
public class StringConverters {

	private final static Logger logger = LoggerFactory.getLogger(StringConverters.class);

	public final static String DATE_FORMAT_FULL = "yyyy-MM-dd HH:mm:ss";
	public final static String DATE_FORMAT_YEAR_MONTH_DAY = "yyyy-MM-dd";
	private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

	/**
	 * 将传入的参数转换为Date类型并返回
	 *
	 * @param convertString 需要转换的参数
	 * @return Converted Date Object.
	 */
	public static Date ToDateOnly(String convertString) {
		return ToDatePattern(convertString, DATE_FORMAT_YEAR_MONTH_DAY, "");
	}

	public static Date ToDateTime(String convertString) {
		return ToDatePattern(convertString, DATE_FORMAT_FULL, "");
	}

	/**
	 * 将传入的参数转换为Date类型并返回
	 *
	 * @param convertString 需要转换的参数
	 * @param pattern       日期转换格式匹配
	 * @return Converted Date Object.
	 */
	public static Date ToDatePattern(String convertString, String pattern) {
		return ToDatePattern(convertString, pattern, "");
	}

	/**
	 * 将传入的参数转换为Date类型并返回
	 *
	 * @param convertString 需要转换的参数
	 * @param pattern       日期转换格式匹配
	 * @param paramDesc     需要转换的参数说明(作为日志补充)
	 * @return Converted Date Object.
	 */
	public static Date ToDatePattern(String convertString, String pattern, String paramDesc) {

		pattern = CommonSugar.getStringDefault(pattern, DATE_FORMAT_FULL);

		Date result = null;
		if (!StringUtils.isEmpty(convertString)) {
			try {
				SimpleDateFormat sdf = new SimpleDateFormat(pattern);
				sdf.setLenient(false);
				result = sdf.parse(convertString);
				logger.debug("转换成功[String-Date]，输入参数[{}]为[{}]", paramDesc, convertString);
			} catch (Exception ex) {
				logger.error("转换失败[String-Date]，输入参数[{}]为[{}]", paramDesc, convertString);
			}
		} else {
			logger.debug("转换失败[String-Date]，输入参数[{}]为[{}]", paramDesc, convertString);
		}
		return result;
	}


	/**
	 * 将传入的参数转换为Integer类型并返回
	 *
	 * @param convertString 需要转换的参数
	 * @return Converted Integer Object.
	 */
	public static Integer ToInteger(String convertString) {
		return ToInteger(convertString, "字符串");
	}

	/**
	 * 将传入的参数转换为Integer类型并返回
	 *
	 * @param convertString 需要转换的参数
	 * @param paramDesc     需要转换的参数说明(作为日志补充)
	 * @return Converted Integer Object.
	 */
	public static Integer ToInteger(String convertString, String paramDesc) {

		Integer result = null;
		if (!StringUtils.isEmpty(convertString)) {
			try {
				result = Integer.parseInt(convertString);
				logger.debug("转换成功[String-Integer]，输入参数[{}]为[{}]", paramDesc, convertString);
			} catch (Exception ex) {
				logger.error("转换失败[String-Integer]，输入参数[{}]为[{}]", paramDesc, convertString);
			}
		} else {
			logger.debug("转换失败[String-Integer]，输入参数[{}]为[{}]", paramDesc, convertString);
		}
		return result;
	}


	/**
	 * 将传入的参数转换为Long类型并返回
	 *
	 * @param convertString 需要转换的参数
	 * @return Converted Long Object.
	 */
	public static Long ToLong(String convertString) {
		return ToLong(convertString, "字符串");
	}

	/**
	 * 将传入的参数转换为Long类型并返回
	 *
	 * @param convertString 需要转换的参数
	 * @param paramDesc     需要转换的参数说明(作为日志补充)
	 * @return Converted Long Object.
	 */
	public static Long ToLong(String convertString, String paramDesc) {

		Long result = null;
		if (!StringUtils.isEmpty(convertString)) {
			try {
				result = Long.parseLong(convertString);
				logger.debug("转换成功[String-Long]，输入参数[{}]为[{}]", paramDesc, convertString);
			} catch (Exception ex) {
				logger.error("转换失败[String-Long]，输入参数[{}]为[{}]", paramDesc, convertString);
			}
		} else {
			logger.debug("转换失败[String-Long]，输入参数[{}]为[{}]", paramDesc, convertString);
		}

		return result;
	}

	/**
	 * 将传入的参数转换为Float类型并返回
	 *
	 * @param convertString 需要转换的参数
	 * @return Converted Float Object.
	 */
	public static Float ToFloat(String convertString) {
		return ToFloat(convertString, "字符串");
	}

	/**
	 * 将传入的参数转换为Float类型并返回
	 *
	 * @param convertString 需要转换的参数
	 * @param paramDesc     需要转换的参数说明(作为日志补充)
	 * @return Converted Float Object.
	 */
	public static Float ToFloat(String convertString, String paramDesc) {

		Float result = null;
		if (!StringUtils.isEmpty(convertString)) {
			try {
				result = Float.parseFloat(convertString);
				logger.debug("转换成功[String-Double]，输入参数[{}]为[{}]", paramDesc, convertString);
			} catch (Exception ex) {
				logger.error("转换失败[String-Double]，输入参数[{}]为[{}]", paramDesc, convertString);
			}
		} else {
			logger.debug("转换失败[String-Double]，输入参数[{}]为[{}]", paramDesc, convertString);
		}

		return result;
	}

	/**
	 * 将传入的参数转换为Double类型并返回
	 *
	 * @param convertString 需要转换的参数
	 * @return Converted Double Object.
	 */
	public static Double ToDouble(String convertString) {
		return ToDouble(convertString, "字符串");
	}

	/**
	 * 将传入的参数转换为Double类型并返回
	 *
	 * @param convertString 需要转换的参数
	 * @param paramDesc     需要转换的参数说明(作为日志补充)
	 * @return Converted Double Object.
	 */
	public static Double ToDouble(String convertString, String paramDesc) {

		Double result = null;
		if (!StringUtils.isEmpty(convertString)) {
			try {
				result = Double.parseDouble(convertString);
				logger.debug("转换成功[String-Double]，输入参数[{}]为[{}]", paramDesc, convertString);
			} catch (Exception ex) {
				logger.error("转换失败[String-Double]，输入参数[{}]为[{}]", paramDesc, convertString);
			}
		} else {
			logger.debug("转换失败[String-Double]，输入参数[{}]为[{}]", paramDesc, convertString);
		}

		return result;
	}


	public static int null2Int(Object s) {
		int v = 0;
		if (s != null)
			try {
				v = Integer.parseInt(s.toString());
			} catch (Exception e) {
			}
		return v;
	}

	public static BigDecimal null2BigDecimal(Object s) {
		BigDecimal v = BigDecimal.ZERO;
		if (s != null)
			try {
				v = new BigDecimal(s.toString());
			} catch (Exception e) {
			}
		return v;
	}

	public static float null2Float(Object s) {
		float v = 0.0f;
		if (s != null)
			try {
				v = Float.parseFloat(s.toString());
			} catch (Exception e) {
			}
		return v;
	}

	public static double null2Double(Object s) {
		double v = 0.0;
		if (s != null)
			try {
				v = Double.parseDouble(null2String(s));
			} catch (Exception e) {
			}
		return v;
	}

	public static boolean null2Boolean(Object s) {
		boolean v = false;
		if (s != null)
			try {
				v = Boolean.parseBoolean(s.toString());
			} catch (Exception e) {
			}
		return v;
	}

	public static String null2String(Object s) {
		return s == null ? "" : s.toString().trim();
	}

	public static Long null2Long(Object s) {
		Long v = -1l;
		if (s != null)
			try {
				v = Long.parseLong(s.toString());
			} catch (Exception e) {
			}
		return v;
	}

	/**
	 * 产生一定长度的字符串
	 * @param length
	 * @return
	 */
	public static String getRandomString(int length){
		//定义一个字符串（A-Z，a-z，0-9）即62位；
		String str="zxcvbnmlkjhgfdsaqwertyuiopQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
		//由Random生成随机数
		Random random=new Random();
		StringBuffer sb=new StringBuffer();
		//长度为几就循环几次
		for(int i=0; i<length; ++i){
			//产生0-61的数字
			int number=random.nextInt(62);
			//将产生的数字通过length次承载到sb中
			sb.append(str.charAt(number));
		}
		//将承载的字符转换成字符串
		return sb.toString();
	}

	/**
	 * 产生一定长度的数字字符串
	 * @param length
	 * @return
	 */
	public static String getRandomNum(int length){
		//定义一个字符串（0-9）10；
		String str="1234567890";
		//由Random生成随机数
		Random random=new Random();
		StringBuffer sb=new StringBuffer();
		//长度为几就循环几次
		for(int i=0; i<length; ++i){
			//产生0-61的数字
			int number=random.nextInt(10);
			//将产生的数字通过length次承载到sb中
			sb.append(str.charAt(number));
		}
		//将承载的字符转换成字符串
		return sb.toString();
	}

	public static Date formatDate(String s) {
		Date d = null;
		try {
			d = dateFormat.parse(s);
		} catch (Exception e) {
		}
		return d;
	}

	public static Date formatDate(String s, String format) {
		Date d = null;
		try {
			SimpleDateFormat dFormat = new SimpleDateFormat(format);
			d = dFormat.parse(s);
		} catch (Exception e) {
		}
		return d;
	}

	public static String formatTime(String format, Object v) {
		if (v == null)
			return null;
		if (v.equals(""))
			return "";
		SimpleDateFormat df = new SimpleDateFormat(format);
		return df.format(v);
	}

	public static String formatLongDate(Object v) {
		if (v == null || v.equals(""))
			return "";
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return df.format(v);
	}

	public static String formatShortDate(Object v) {
		if (v == null)
			return null;
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		return df.format(v);
	}

	public static Date parseShortDate(String dateStr) throws ParseException {

		if (dateStr == null)
			return null;
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		return df.parse(dateStr);
	}

	public static Date parseLongDate(String dateStr) throws ParseException {

		if (dateStr == null)
			return null;
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return df.parse(dateStr);
	}


	public static Date beforeDate(Date date,int num){
		//SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_MONTH, -num);
		date = calendar.getTime();
		return date;

	}

	public static String decode(String s) {
		String ret = s;
		try {
			ret = URLDecoder.decode(s.trim(), "UTF-8");
		} catch (Exception e) {
		}
		return ret;
	}

	public static String encode(String s) {
		String ret = s;
		try {
			ret = URLEncoder.encode(s.trim(), "UTF-8");
		} catch (Exception e) {
		}
		return ret;
	}

}
